<template>
  <div id="earthquakeImpactField-map" style="width:100%;"></div>
</template>
<script>
import '@/assets/map/ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import { getProjection,getResolutions,getTiandituVecMap,getTiandituVecText,getTiandituImgMap,getTiandituImgText,
  getRESTLayer,getVectorTileLayer,iServerHttp,meterToDegree } from "@/map/projMap.js";
import VectorLayer from 'ol/layer/Vector';
import {Cluster, Vector as VectorSource, XYZ} from 'ol/source'
import {boundingExtent} from 'ol/extent';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import WKT from 'ol/format/WKT';

export default {
  name: "earthquakeImpactField",
  components: {

  },
  props:{
    geomList: {//全部序号列表
      type:Array,
      required:true,
      default:[]
    },
  },
  emits:["selectLonLat"],
  data() {
    return {
      str: "earthquakeImpactField",
      map: null,
      center: [105, 34],
      zoom: 4,
      layer1:null,//天地图街道图
      layer2:null,
      ellipseLayer: null,
    }
  },
  watch: {
    geomList: {//全部序号列表
      handler: function(newVal,oldVal){
        if(newVal.length != 0){
          this.showInfluenceEllipse(newVal);
        }
      },
      immediate:true
    },
  },
  mounted() {
    console.log("mounted");
    let that = this;
    //地图异步加载
    this.$nextTick(function(){
      console.log('地图异步加载');
      //地图异步加载
      setTimeout(() => {
        //初始化地图信息
        that.initMap();
      }, 200);
    });
  },
  methods: {
    initMap() {
      let that = this;
      let mapStr = this.str;
      let targetMap = document.getElementById(mapStr+"-map");
      if(targetMap.innerHTML!=""){
        console.log("清空targetMap");
      }
      targetMap.innerHTML = "";//清空
      //自动获取地图div高度
      this.autodivheight();
      //浏览器窗口发生变化时同时变化DIV高度
      window.onresize=this.autodivheight;
      if(this.map){//避免重复加载地图
        console.log("避免重复加载地图");
        return;
      }
      console.log("初始化地图");
      //获取投影4490坐标系
      this.projection4490 = getProjection();
      //初始化地图信息
      this.map = new Map({
        target: targetMap.id,
        view: new View({
          center: this.center,
          maxZoom: 18,
          minZoom: 4,
          zoom: this.zoom,
          constrainResolution:true,//缩放地图可移动到最近的缩放级别（整数zoom级别）
          projection: 'EPSG:4490',
        })
      });
      //添加天地图图层
      this.layer1 = getTiandituVecMap();//fxpc天地图街道影像底图
      this.map.addLayer(this.layer1);
      this.layer2 = getTiandituVecText();//fxpc天地图街道地图注记
      this.map.addLayer(this.layer2);
      this.layer1.setZIndex(0);
      this.layer2.setZIndex(0);
      //椭圆地震影响场图层
      this.ellipseLayer = new VectorLayer({
        source: new VectorSource({
          wrapX: false
        }),
        projection: 'EPSG:4490',
      });
      this.map.addLayer(this.ellipseLayer);
      this.ellipseLayer.setZIndex(4);
      this.map.on('click',function(event){
        let coordinate = that.map.getEventCoordinate(event.originalEvent)
        that.$emit('selectLonLat',coordinate)
      })
    },
    showInfluenceEllipse(list) {
      this.ellipseLayer.getSource().clear();
      let colorArray = ["rgba(140,0,0,0.7)","","","",""];
      let allCoordinates = [];//全部经纬度
      for(let i = 0;i < list.length;i++) {
        let featureTmp = new WKT().readFeature(list[i].geom);
        let levelData = ['','','','','']
        let colors = [
          {levle: '10',name:'Ⅹ（10度）',color: 'rgba(140,0,0,0.7)'},
          {levle: '9',name:'Ⅸ（9度）',color: 'rgba(168,0,0,0.7)'},
          {levle: '8',name:'Ⅷ（8度）',color: 'rgba(200,40,40,0.7)'},
          {levle: '7',name:'Ⅶ（7度）',color: 'rgba(255,127,127,0.7)'},
          {levle: '6',name:'Ⅵ（6度）',color: 'rgba(255,190,190,0.7)'},
        ]
        let objectData = colors.find(item => item.levle == list[i].dzIntensity)
        //样式
        let style = this.getPolyonTextStyle("rgb(152,152,152)", objectData.color, objectData.name);
        featureTmp.setStyle(style);
        //添加地震影响场椭圆
        this.ellipseLayer.getSource().addFeature(featureTmp);
        //获取范围
        let extent = featureTmp.getGeometry().getExtent();
        if(extent.length==4){
          //全部经纬度--左下角
          allCoordinates.push([extent[0],extent[1]]);
          //全部经纬度--右上角
          allCoordinates.push([extent[2],extent[3]]);
        }
      }
      //缩放到区域位置
      this.showBoundingExtent(allCoordinates);
    },
    //缩放到区域位置
    showBoundingExtent(coordinates){
      console.log("缩放到区域位置");
      if (this.map!=null && coordinates!=null && coordinates.length > 1) {
        //console.log(coordinates);
        let extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
        //获取默认位置
        //this.center = this.map.getView().getCenter();
        //this.zoom = this.map.getView().getZoom();
      }
    },
    getPolyonTextStyle(color,backgroundColor,text){//多边形文字样式
      if(backgroundColor==null){
        backgroundColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:backgroundColor
        }),
        stroke:new Stroke({//描绘
          width:1,//宽
          color:color
        }),
        text: new Text({
          text: text,
          fill: new Fill({
            color: 'black'
          }),
          offsetY:20,
          font:'bold 14px 微软雅黑',
        })
      });

      return style;
    },
    autodivheight() {//自动获取div高度
      //获取浏览器窗口高度
      let winHeight = 0;
      if (window.innerHeight) {
        winHeight = window.innerHeight;
      } else if ((document.body) && (document.body.clientHeight)) {
        winHeight = document.body.clientHeight;
      }
      //通过深入Document内部对body进行检测，获取浏览器窗口高度
      if (document.documentElement && document.documentElement.clientHeight) {
        winHeight = document.documentElement.clientHeight;
      }
      //全屏时窗口高度:864px,地图div高度:754px
      let tempHeight = 864;
      let mapTempHeight = 754;
      let mapHeight = winHeight - tempHeight + mapTempHeight;
      //最小高度
      if(mapHeight<480){
        mapHeight = 480;
      }
      //设置地图高度
      document.getElementById(this.str+"-map").style.height= mapHeight +"px";
      console.log("窗口高度："+winHeight+"地图高度："+mapHeight);
      //resize事件--刷新地图,确保地图不变形
      if(this.map){
        this.map.updateSize();
        console.log("resize事件--刷新地图,确保地图不变形");
      }
    },
  }
}
</script>